/**
 * Created by zhou on 2017/3/28.
 * update yanglq
 */

/**
 * 首页消息通知功能
 */
//     <script type='text/javascript' src='http://192.168.5.48:7001/ta3message-server/dwr/engine.js'></script>
//     <script type='text/javascript' src='http://192.168.5.48:7001/ta3message-server/dwr/util.js'></script>
//     <script type='text/javascript' src='http://192.168.5.48:7001/ta3message-server/dwr/interface/dwrController.js'></script>

/* 首页通知 通用function */
/**
 * 通知初始化
 */
var messageServerPath="http://127.0.0.1:8001/ta3message";
var messageServerPath_ws="127.0.0.1:8001/ta3message";
/*var messageServerPath="http://192.168.17.63:7009/ta3message-server";
var messageServerPath_ws="192.168.17.63:7009/ta3message-server";*/
/*var messageServerPath="http://127.0.0.1:8080";
var messageServerPath_ws="127.0.0.1:8080";*/
var messageIM_ip="192.168.17.64";
var messageIM_port=5222;
function initStyle(type,systemid,userid,pageid){
    useType = type;
    now_systemid =  systemid;
    now_userid = userid;
    var tmSwitch = '<div id="tmSwitch" onclick="fnShowMg()"><p>通知</p></div>';
    var showBox = '<div id="mgShowBox">'
        +'<div id="msb_h">'
            +'<a href="javascript:void(0)">消息面板</a>'
        +'</div>'
        +'<div id="msb_left"><ul id="msb_menu_ul"></ul></div>'
        +'<div id="msb_center">'
            +'<div id="msb_c"></div>'
            +'<div id="msb_c_atm"></div>'
        +'</div>'
        +'<div id="msb_f" style="">'
            +'<input id="msb_b3" value="关闭" type="button" onclick="closeMsb()" />'
            +'<a id="from_name">发送人</a>'
        +'</div></div>'
    $("body").append(tmSwitch).append(showBox);
    $('#msb_h').mousedown(
        function (event) {
            var isMove = true;
            var abs_x = event.pageX - parseInt($('#mgShowBox').css('left'));
            var abs_y = event.pageY - parseInt($('#mgShowBox').css('top'));
            $(document).mousemove(function (event) {
                    if (isMove) {
                        var obj = $('#mgShowBox');
                        obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y});
                    }
                }
            ).mouseup(
                function () {
                    isMove = false;
                }
            );
        }
    );
    if(type=="dwr"){
        initDwr(systemid,userid,pageid);
    }else if(type=="redis"){
        initRedisCache(systemid,userid);
    }else if(type=="webSocket"){
        initWebSocket(systemid,userid);
    }else if(type=="im"){
        now_messageType = "5";
        initIM(userid,messageIM_ip,messageIM_port);

    }else{
        alert("未选择通知使用类型");
    }
}
var mgRecord = [];  //保存通知
var mghead_r = 0;   // 是否重新获取通知
var mgRid; //记录当前打开的通知 id
var now_systemid;
var now_userid;
var now_messageType="0";
var useType = null;
function fnShowMg(){
    $("#mgShowBox").css("display","block");
    if(!mghead_r){
        if(mgRecord.length){
            var html ="";
            for(var i=0;i<mgRecord.length;i++){
                if(mgRecord[i].read == 1){
                    html+="<li onclick='showMgContent(this)'>"+
                        "<div class='used_menu_name' style='width: 120px;color:brown;'>"+mgRecord[i].title+"</div></li>";
                }else{
                    html+="<li class='unread' onclick='showMgContent(this)'>"+
                        "<div class='used_menu_name' style='width: 120px;'>"+mgRecord[i].title+"</div></li>";
                }
            }
            $("#msb_menu_ul").html(html);
        }else{
            $("#msb_menu_ul").html("<li><div class='used_menu_name'>没有消息</div></li>");
        }
        mghead_r=1;
    }
    var $tmSwitch = $("#tmSwitch");
    $tmSwitch.html("<p>通知</p>");
}
function showMgContent(liobj){
    $(liobj).parent().find(".used_menu_name").css("background","white");
    $(liobj).children(".used_menu_name").css("background","burlywood");
    var index = $(liobj).index();
    mgRid = mgRecord[index].mgid;
    var html="<div style=\"padding-top:6px;text-align:center;height:8%;background:url('indexue/indexresource/images/home_ico.png') 0 -247px;\">"+mgRecord[index].title+"</div>"+
        "<div style='height:88%;padding-top:5px;overflow:auto;'>"+mgRecord[index].content+"</div>";
    $("#msb_c").html(html);
    $("#msb_c_atm").html(mgRecord[index].attachment);
    $("#from_name").html("from: "+mgRecord[index].sname +" , "+mgRecord[index].mgdateShow.substr(0,11));
    // $("#mgShowBox").css("display","block");
    if($(liobj).hasClass("unread")){
        /**
         * fixme
         */
        if(useType=="dwr"){
            dwrController.readMessage(mgRid,now_systemid,now_userid);
        }else{
            fnReadMessageByHttp(mgRid,now_systemid,now_userid);
        }
        mgRecord[index].read=1;
        mghead_r=0;
    }
}

function dealAllMessage(data){
    mgRecord = data;
    mghead_r = 0;
    newMessage();
}
function newMessage(){
    var newMg = 0;
    for(var i=0;i<mgRecord.length;i++){
        if(mgRecord[i].read != '1'){
            newMg++;
        }
    }
    if(newMg){
        $("#tmSwitch").html("<p style='color:red'>通知("+newMg+")</p>");
    }
}
function mgPoint(msg){
    var $alertBox = $('<div class="tm_alertBox" style="display:none;">'+
        '<h2 onclick="mgPoint_remove(this)">'+msg.title+'</h2>'+
        '<p onclick="mgPoint_show(this)">'+msg.content+'</p>'+
        '</div>');
    $("body").append($alertBox);
    $alertBox.slideDown("slow",function(){
           setTimeout(function(){
         $alertBox.slideUp("slow",function(){
         $alertBox.remove();
         });
         },5000);
    });
}
function mgPoint_remove(obj){
    var $p = $(obj).parent();
    $p.slideUp("slow",function(){
        $p.remove();
    });
}
function mgPoint_show(obj){
    var $p = $(obj).parent();
    $p.slideUp("slow",function(){
        $p.remove();
    });
}

function closeMsb(){
    $("#mgShowBox").css("display","none");
}

/* 首页通知 通用function  end */

/* dwr */
function initDwr(systemid,userid,pageid){
	dwr.engine.setOverridePath(messageServerPath+"/dwr");
    dwr.engine.setActiveReverseAjax(true);
	dwr.engine.setNotifyServerOnPageUnload(true);
	dwr.engine.setErrorHandler(function(message, ex){
		dwr.engine._debug("Error: " + ex.name + ", " + ex.message, true);
	});
	var intervalsArray = [1,3,10];
	dwr.engine.setRetryIntervals(intervalsArray);
	dwr.engine.setMaxRetries(100);
	dwrController.onPageLoad(systemid,userid,pageid);

    // fngetMessageDwr(systemid,userid);
}
/**
 * 页面加载查询通知 dwr
 * @param systemid
 * @param userid
 */
function fngetMessageDwr(systemid,userid){
    dwrController.queryMessage(systemid,userid,function(data){
        dealAllMessage(data);
    });
}
/**
 * 附件下载  dwr
 * @param fileid
 */
function mgAtmDownloadDwr(fileid){
//	var url = "<%=basePath%>message/messageSend!mgAtmDownload.do" +"?_download_fileName="+name+"&_download_file="+mgRid;
//	location.href = url;
    dwrController.downloadFile(fileid,function(data){
        data = "http://192.168.5.60:8082/"+data;
        dwr.engine.openInDownload(data);
    });
}
/**
 * 服务器消息推送 dwr
 * @param msg
 */
function messageDwr(msg){
    console.log(msg);
    mgRecord.push(msg);
    mghead_r = 0;
    mgPoint(msg);
}
/*dwrEnd*/
/* webSokcet*/
 function initWebSocket(systemid,userid){
     var websocket;
     if ('WebSocket' in window) {
         websocket = new WebSocket("ws://"+messageServerPath_ws+"/webSocketServer");
     } else if ('MozWebSocket' in window) {
         websocket = new MozWebSocket("ws://"+messageServerPath_ws+"/webSocketServer");
     } else {
         websocket = new SockJS("http://"+messageServerPath_ws+"/sockjs/webSocketServer");
     }

     websocket.onopen = function(event) {
         console.log("webSocket open");
         websocket.send(systemid+"_"+userid);
     };
     websocket.onmessage = function(event) {
         messageDwr(JSON.parse(event.data));
     };
     websocket.onerror = function(event) {
         console.log("webSocket连接断开");
     };
     websocket.onclose = function(event) {
         console.log("webSocket连接关闭");
     }

     fnGetMessageByHttp(systemid,userid);
 }
 /*webSokcet end*/

/* redis Cache*/
function initRedisCache(systemid,userid){
    now_systemid =  systemid;
    now_userid = userid;
    fnGetMessageByHttp(systemid,userid);
    fnUserOnline(systemid,userid,"on");
}

function fnGetMessageByHttp(systemid,userid){
    var param ="{'systemid':'"+systemid+"','userid':'"+userid+"','messageType':'"+now_messageType+"'}";
    $.ajax({
        url:messageServerPath+"/messageHttp/messageSearchController!queryMessage.do",
//            dataType: 'jsonp',
        data:{"searchParameter":param},
        success:function(data){
            dealAllMessage(eval(data));
        }
    });
}
function fnReadMessageByHttp(mgid,systemid,userid){
    $.ajax({
        url:messageServerPath+"/messageHttp/messageSearchController!readMessage.do",
        data:{"mgid":mgid,"systemid":systemid,"userid":userid,"messageType":now_messageType}
    });
}
function fnUserOnline(systemid,userid,online){
    $.ajax({
        url:messageServerPath+"/messageHttp/messageSearchController!userOnline.do",
        data:{"systemid":systemid,"userid":userid,"online":online},
        success:function(data){
            console.log(data);
        }
    });
}
function fngetMessageCache(systemid,userid){
    $.ajax({
        url:messageServerPath+"/messageHttp/messageSearchController!getMessageByCache.do",
        data:{"systemid":systemid,"userid":userid},
        success:function(data){
            console.log(data);
        }
    });
}

window.onunload = function() {
	if(useType=="im"){
        _IMUtil.imLogout(now_userid, messageIM_ip);
	}
}
/* end Redis*/

/* im*/
function initIM(userid,ip,port){
    if (typeof _IMUtil !== 'undefined') {
        _IMUtil.imLogin(userid, ip, port, function(callBackMsg){
            console.log(callBackMsg);
        });
    }
    fnGetMessageByHttp(now_systemid,now_userid);
}
function ReceiveImMsg(msg) {
    // console.log(msg);
    messageDwr(msg);
}
/* end im*/